/**
 * Created by rekey on 13-12-13.
 */
var fs = require('fs');
var path = require('path');
var request = require('request');
var crypto = require('./crypto.js');
var toPromise = require('./toPromise.js');
var os = require('os');
var tmpDir = os.tmpDir();

function getReferer(url) {
  var ret = '';
  if (url.indexOf('so.qhimg.com') > -1) {
    ret = 'http://image.so.com';
  }
  if (url.indexOf('.ykimg.com') > -1) {
    ret = 'http://www.youku.com';
  }
  return ret;
}

function down(url, output, callback) {
  var data = {
    headers: {
      'referer': getReferer(url),
      'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'
    },
    timeout: 5000
  };
  request.get(url, data, function () {
    callback(null, {
      output: output
    });
  }).pipe(fs.createWriteStream(output));
}

module.exports = function (url) {
  var name = crypto.md5(url, true);
  var output = path.resolve(tmpDir, name);
  var exists = toPromise(fs.exists);
  return exists(output).then(function () {
    return toPromise(down)(url, output);
  }, function () {
    return {
      output: output,
      url: url
    };
  });
};